<template>
    <el-form v-if="schema && schema.properties" :inline="true" class="schema-search-bar">
        <!-- 动态组件 -->
        <el-form-item v-for="(schemaItem, key) in schema.properties" :key="key" :label="schemaItem.label">
            <component :ref="handleSearchComList" :is="SearchItemConfig[schemaItem.option?.comType]?.component"
                :schemaKey="key" :schema="schemaItem" @loaded="handleChildLoaded" />
        </el-form-item>
        <!-- 操作区域 -->
        <el-form-item>
            <el-button type="primary" plain class="search-btn" @click="search">搜索</el-button>
            <el-button plain class="reset-btn" @click="reset">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import SearchItemConfig from './schema-item-config';
import { inject, ref } from 'vue'

const { searchSchema } = inject('schemaViewData')
const props = defineProps({
    schema: {
        type: Object,
        default: () => ({})
    }
})
const emit = defineEmits(['search', 'load', 'reset'])

const search = () => {
    emit('search', searchSchema)
}
const load = () => {
    emit('load', searchSchema)
}
const reset = () => {
    searchComList.value.forEach(component => {
        component?.reset()
    })
    emit('search', {})
}

const searchComList = ref([])
const handleSearchComList = (el) => {
    searchComList.value.push(el)
}

const getValue = () => {
    let dtoObj = {}
    searchComList.value.forEach(component => {
        dtoObj = {
            ...dtoObj,
            ...component?.getValue()
        }
    })
    return dtoObj;
}

let childComLoadedCount = 0
const handleChildLoaded = (schemaKey, value) => {
    childComLoadedCount++
    if (childComLoadedCount >= Object.keys(props.schema.properties).length) {
        emit('load', getValue())
    }
    searchSchema[schemaKey] = value
}

defineExpose({
    reset,
    getValue,
    load
})
</script>

<style lang="less">
.schema-search-bar {
    min-width: 500px;

    .input {
        width: 180px;
    }
}

.schema-search-bar .search-btn {
    width: 100px;
}

.schema-search-bar .reset-btn {
    width: 100px;
}
</style>